package profile

import (
	"context"
	"gitee.com/alex_li/amazon-rpt/cmd/rpt/process/common"
	"gitee.com/alex_li/amazon-rpt/internal/db"
	"gitee.com/alex_li/amazon-rpt/internal/sdk/advertising"
	"github.com/lishimeng/app-starter"
	"github.com/lishimeng/app-starter/persistence"
	"github.com/lishimeng/go-log"
	"time"
)

func UpdateProfiles(ctx context.Context) {
	var clientIndex int
	for {
		select {
		case <-ctx.Done():
			return
		case <-time.After(time.Second * 5):
			client, err := common.GetClient(clientIndex)
			if err != nil {
				log.Info(err)
				log.Info("exit update profile process")
				return
			}
			clientIndex = client.Id
			updateProfile(client)
		}
	}
}

func updateProfile(client db.AmazonLwa) {
	var err error

	log.Info("update client profiles: %s", client.ClientId)

	var list []db.AmazonAdsProfile
	_, err = app.GetOrm().Context.QueryTable(new(db.AmazonAdsProfile)).Filter("ClientId", client.ClientId).All(&list)
	if err != nil {
		log.Info(err)
		return
	}
	if len(list) > 0 {
		log.Info("update profile success")
		return
	}

	sdk, err := common.CreateSdk(client)
	if err != nil {
		log.Info(err)
		return
	}
	err = sdk.GetProfile(func(clientId string, profiles ...advertising.Profile) {
		go saveProfile(clientId, profiles...)
	})
	if err != nil {
		log.Info(err)
		return
	}
}
func saveProfile(clientId string, profiles ...advertising.Profile) {
	// 只保存US类型
	if len(profiles) == 0 {
		return
	}
	var has = false
	var profile advertising.Profile
	for _, v := range profiles {
		if v.CountryCode == "US" {
			has = true
			profile = v
			break
		}
	}
	if !has {
		return
	}
	err := app.GetOrm().Transaction(func(tx persistence.TxContext) (e error) {
		var list []db.AmazonAdsProfile
		_, e = tx.Context.QueryTable(new(db.AmazonAdsProfile)).
			Filter("ClientId", clientId).
			All(&list)
		if e != nil {
			return
		}
		if len(list) > 0 {
			for _, p := range list {
				_, e = tx.Context.Delete(&p)
			}
		}
		var p db.AmazonAdsProfile
		p.ProfileId = profile.ProfileId
		p.ClientId = clientId
		p.CountryCode = profile.CountryCode
		_, e = tx.Context.Insert(&p)
		return
	})
	if err != nil {
		log.Info(err)
		return
	}
	log.Info("save profile success")
}
